// pages/coupon/coupon.js
// pages/details/details.js
const app = getApp()
var url = require('../../utils/url.js');
var type=0;
var page=1;
var last_page = 0;
var voucherId;
var voucherIdx;
var voucherS;
var token;
var voucherNum;
var couponactve;
var formid;
var loadMore = function (that) {
  wx.showLoading({
    title: '加载中',
  });
  if (page == 1) {
    page = 2
  }
  if (page < last_page || page == last_page) {
    console.log(page)
    wx.request({
      url: url.URl + 'goods/voucher/list',
      data: { page: page ,type:type},
      method: 'get',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(that.data.couponList)
        wx.hideLoading();
        that.setData({
          couponList: that.data.couponList.concat(res.data.data.data)
        });
        page++;
      }
    });
  } else {
    wx.hideLoading();
    that.setData({
      nodata: 1,
      skill: true
    })
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banner:"",
    couponNav:["免费领取","购买更多"],
    couponList:[],
    couponactve:0,
    freeW:true,
    num:1,
    limitNum:"",
    msg:"",
    active:"0"
  },
  onClick(event) {
    var that=this;
    console.log(event)
    var idx = event.detail.index;
    couponactve = that.data.couponactve;
    if (idx == couponactve){
      return false;
    }else{
      console.log(idx)
      type=idx;
      page=1;
      that.setData({
        couponactve:idx,
        couponList:[],
        num:1
      })
      that.getList()
    }
  },
  close:function(){
    this.setData({
      freeW:true
    })
  },
  toBUY: function (e) {
    var that=this;
    formid = e.detail.formId
    if(token){
      var item = e.currentTarget.dataset.item;
      var itemJson = JSON.stringify(item)
      wx.navigateTo({
        url: '/pages/couponBuy/couponBuy?item=' + itemJson,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }else{
      app.onGotUserInfo(e, that, formid)
    }
    
  },
  free:function(e){
    console.log(e)
    var that=this;
    formid = e.detail.formId
    this.setData({
      formid: formid
    })
    if (token){
      that.setData({
        num: 1,
        maxNum: 0
      })
      voucherId = e.currentTarget.dataset.id;
      voucherIdx = e.currentTarget.dataset.index;
      voucherS = e.currentTarget.dataset.storage;
      voucherNum = e.currentTarget.dataset.num;
      var limitNum = e.currentTarget.dataset.limit;
      if (limitNum != 0) {
        if (limitNum <= voucherS) {
          that.setData({
            maxNum: limitNum,
            msg: "不能超出限购"
          })
        } else {
          that.setData({
            maxNum: voucherS,
            msg: "不能超出库存"
          })
        }
      } else {
        that.setData({
          maxNum: voucherS,
          msg: "不能超出库存"
        })
      }
      that.setData({
        limitNum: limitNum
      })
      console.log(e)
      this.setData({
        freeW: false
      })
    }else{
      app.onGotUserInfo(e, that, formid)
    }
    
  },
  onChange:function(e){
    console.log(e)
    var that = this
    var maxNum = this.setData.maxNum;
    var msg = this.data.msg;
    var totalFee = that.data.totalFee;
    var detail = e.detail;
    this.setData({
      async: true
    })
    if (detail > maxNum) {
      wx.showToast({
        title: msg,
        icon: 'none',
      })
    } else {
      this.setData({
        num: detail,
      })
    }
  },
  overlimit: function (e) {
    var detail = e.detail;
    var msg = this.data.msg
    if (detail == "plus") {
      wx.showToast({
        title: msg,
        icon: 'none',
      })
    }
  },
  plus: function (e) {
   
    if (voucherS < voucherNum){
      wx.showToast({
        title: '优惠券数量不足',
        icon: 'none',
      })
    }else{
      voucherNum++
      voucherS--
    }
  },
  minus: function (e) {
    console.log(e)
    voucherNum--
    voucherS++
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if(options.type){
      console.log(type,1)
      type=1;
      that.setData({
        active:1,
        couponactve:1
      })
      console.log(that.data)
      that.getList()
    }else{
      that.getList()
    }
    that.getAds()
    
    wx.getStorage({
      key: 'token',
      success: function(res) {
        token=res.data
      },
    })
  },
  getAds() {
    var that = this;
    wx.showLoading({
      title: '加载中..',
    })
    wx.request({
      url: url.URl + 'goods/voucher/ads',
      data: {},
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var msg = res.data.msg;
        wx.hideLoading()
        console.log(res)
        if (res.data.code == 200) { 
          that.setData({
             banner:res.data.data
          })
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  getList() {
    var that = this;
    if (page > 1) {
      page--;
    }
    wx.showLoading({
      title: '加载中..',
    })
    wx.request({
      url: url.URl + 'goods/voucher/list',
      data: {type:type,page:page},
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var msg = res.data.msg;
        console.log(res)
        if (res.data.code == 200) {
          last_page = res.data.data.last_page
          var couponList = res.data.data.data;
          for (var i = 0; i < couponList.length;i++){
            couponList[i].num=1;
          }
          that.setData({
            couponList: couponList
          })
          wx.hideLoading()
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  
  tobuy:function(e){
    var that=this;
    var num = that.data.num;
    wx.request({
      url: url.URl + 'goods/voucher/tobuy',
      data: { id: voucherId, num: num },
      method: 'post',
      header: {
        'Authorization': token
      },
      success: function (res) {
        var msg = res.data.msg;
        console.log(res)
        if (res.data.code == 200) {
         wx.showToast({
           title: msg,
           success:function(){
             wx.navigateTo({
               url: '/pages/myCoupon/myCoupon'
             })
           }
         })
          wx.hideLoading()
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.getStorage({
      key: 'token',
      success: function (res) {
        token = res.data
      },
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    type=0;
    page=1;
    couponactve=0;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log(page)
    var that = this;
    if (that.data.index != 0) {
      loadMore(that)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})